/** http工具类,用于设置请求拦截器和响应拦截器 */
import Request from 'luch-request';
import { assign } from 'lodash-es';
import { Toast } from '@/utils/uniapi/prompt';
import { getEnvValue } from '@/utils/env';
import { useAuthStore } from '@/store/modules/auth';
import { ResultEnum } from '@/enums/httpEnum';
import { router } from '../router';
import config from '../config';

const BASE_URL: string = import.meta.env.VITE_API_URL;

// 请求头
const HEADER = {
  'Content-Type': 'application/json;charset=UTF-8;',
  Accept: 'application/json, text/plain, */*',
};

// 放行url
const ANON_URL = [
  config.url.login,
  config.url.logout,
  config.url.register_user,
  config.url.reset_pwd,
  config.url.refresh_token,
];

function createRequest() {
  return new Request({
    // 默认请求地址，可在 .env.** 文件中修改
    baseURL: BASE_URL,
    // 设置超时时间
    timeout: ResultEnum.TIMEOUT as number,
    // 设置请求头
    header: HEADER,
    custom: {
      auth: true,
    },
  });
}

const request = createRequest();

/**
 * 请求拦截器
 */
request.interceptors.request.use(
  (options) => {
    const url = ANON_URL.filter((item: string) => options.url && options.url.indexOf(item) != -1);
    if (options.custom?.auth && url.length == 0) {
      const authStore = useAuthStore();
      if (!authStore.isLogin) {
        router.reLaunch(config.route.login);
        return Promise.reject(options);
      }

      options.header = assign(options.header, {
        token: authStore.token,
      });
    }
    return options;
  },
  (options) => {
    return Promise.reject(options);
  },
);

/**
 * 响应拦截器
 */
request.interceptors.response.use(
  async (response) => {
    const { data: resData } = response;
    const { code, msg } = resData;
    if (code === ResultEnum.SUCCESS) {
      return response as any;
    } else if (code === ResultEnum.OVERDUE) {
      Toast(msg);
      router.reLaunch(config.route.login);
      return Promise.reject(resData);
    }
    return Promise.reject(resData);
  },
  (response) => {
    // 请求错误做点什么。可以使用async await 做异步操作
    // error('Request Error!');
    return Promise.reject(response);
  },
);

export { request, BASE_URL };
